<template>
  <div class="login-container" @scroll="handleScroll" @touchmove="handleTouchMove">
    <div class="login-img">
      <img :src="logoImg" alt="" />
    </div>

    <div class="login-form" id="loginForm">
      <div class="card-content">
        <h3 class="login-title">验证码校验</h3>

        <div class="login-desc">
          为保障账号安全,登录前需验证身份。
          请点击"获取验证码"按钮,并输入邮箱中收到的验证码提交
        </div>

        <div class="form-container">
          <div class="input-group">
            <div class="custom-input-wrapper">
              <div class="custom-input-container">
                <div class="name-top-icon">
                  <van-icon name="completed-o" size="15" />
                </div>
                <input 
                  ref="inputRef"
                  v-model="code"
                  type="text"
                  pattern="[0-9]*"
                  inputmode="numeric"
                  placeholder="请输入验证码"
                  class="custom-input"
                  @focus="handleFocus"
                  @blur="handleBlur"
                  @click="forceFocus"
                />
                <div v-if="showError" class="error-message">请输入验证码</div>
              </div>
              <van-button color="#bf1920" plain class="captcha" :disabled="codeNum > 0" @click="getCode">
                {{ codeNum ? codeNum + 's' : '获取验证码' }}
              </van-button>
            </div>
          </div>

          <div style="margin: 16px;">
            <van-button block type="primary" color="#bf1920" @click="handleSubmit">
              提交{{ loading ? '&nbsp;中...' : '' }}
            </van-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useRouter, useRoute } from "vue-router";
import logoImg from '@/assets/svg/logo.svg'
import { useUserStore } from "@/stores/user";
import { getIsLogin } from '@/utils/storage'
import { getVerifyCode } from "@/api/login";
import { onMounted, onUnmounted, ref, nextTick } from 'vue';

const store = useUserStore();
const router = useRouter();
const route = useRoute();
const codeNum = ref(0);
const code = ref('');
const timer = ref();
const loading = ref(false);
const inputRef = ref(null);
const showError = ref(false);
const isIOS = ref(false);
const isSafari = ref(false);

// 处理页面滚动，使输入框失去焦点，收起键盘
const handleScroll = () => {
  document.activeElement?.blur()
}

// 处理触摸移动事件
const handleTouchMove = () => {
  if (document.activeElement && document.activeElement.tagName === 'INPUT') {
    document.activeElement.blur()
  }
}

// 检测设备和浏览器
onMounted(() => {
  // 检测iOS设备
  isIOS.value = /iPad|iPhone|iPod/.test(navigator.userAgent) && !(window as any).MSStream;
  
  // 检测Safari浏览器
  const ua = navigator.userAgent.toLowerCase();
  isSafari.value = /safari/.test(ua) && !/chrome/.test(ua);
  
  // 初始化处理
  initPageForMobile();
  
  // 添加事件监听
  window.addEventListener('resize', adjustViewForKeyboard);
  document.addEventListener('click', handleDocumentClick);
  
  if (isIOS.value) {
    document.addEventListener('touchend', handleIOSTouch, { passive: false });
    
    // 针对iOS Safari的特殊处理
    if (isSafari.value) {
      // 添加focusin事件监听，确保键盘弹出时滚动到正确位置
      document.addEventListener('focusin', handleIOSFocusIn);
    }
  }
});

// 初始化移动设备页面设置
const initPageForMobile = () => {
  // 防止滚动
  document.body.style.position = 'fixed';
  document.body.style.width = '100%';
  document.body.style.height = '100%';
  document.body.style.overflow = 'hidden';
  
  // 如果是iOS，特别是Safari，需要一些额外的处理
  if (isIOS.value) {
    // 阻止默认的弹性滚动行为
    document.addEventListener('touchmove', (e) => {
      if (e.target !== inputRef.value && e.touches.length > 0) {
        e.preventDefault();
      }
    }, { passive: false });
  }
};

// 处理键盘弹出导致的视图调整
const adjustViewForKeyboard = () => {
  // 延迟处理以确保键盘已完全弹出
  setTimeout(() => {
    if (document.activeElement === inputRef.value) {
      // 使输入框滚动到可见区域
      inputRef.value.scrollIntoView({ block: 'center', behavior: 'smooth' });
    }
  }, 300);
};

// 处理iOS设备上的触摸事件
const handleIOSTouch = (e) => {
  // 如果点击的是输入框，确保获得焦点
  if (e.target === inputRef.value) {
    // 阻止事件冒泡
    e.stopPropagation();
    forceFocus();
  }
  // 如果点击的是按钮，阻止可能导致输入框失焦的行为
  else if (e.target.tagName === 'BUTTON' || e.target.closest('button')) {
    e.stopPropagation();
  }
};

// 处理iOS上的焦点获取事件
const handleIOSFocusIn = (e) => {
  if (e.target === inputRef.value) {
    // iOS Safari中，焦点获取后滚动到可见区域
    setTimeout(() => {
      e.target.scrollIntoView({ block: 'center', behavior: 'smooth' });
    }, 300);
  }
};

// 处理全局点击事件
const handleDocumentClick = (e) => {
  // 如果点击的不是输入框，则让当前输入框失去焦点
  if (e.target !== inputRef.value && 
      e.target.tagName !== 'BUTTON' && 
      !e.target.closest('button') &&
      document.activeElement === inputRef.value) {
    inputRef.value?.blur();
  }
};

// 强制触发输入框获取焦点
const forceFocus = () => {
  if (inputRef.value) {
    // 首先尝试标准焦点方法
    inputRef.value.focus();
    
    // 如果是iOS Safari，使用特殊技巧
    if (isIOS.value && isSafari.value) {
      // 先设为只读，再移除只读状态，强制显示键盘
      inputRef.value.setAttribute('readonly', 'readonly');
      setTimeout(() => {
        inputRef.value.removeAttribute('readonly');
        // 再次尝试获取焦点
        inputRef.value.focus();
        // 选择所有文本可以帮助在某些情况下触发键盘
        inputRef.value.select();
      }, 50);
    }
  }
};

// 处理输入框获取焦点事件
const handleFocus = () => {
  showError.value = false;
  if (inputRef.value && (isIOS.value || isSafari.value)) {
    // 延迟滚动确保键盘弹出后页面在正确位置
    setTimeout(() => {
      inputRef.value.scrollIntoView({ block: 'center', behavior: 'smooth' });
    }, 300);
  }
};

// 处理输入框失去焦点事件
const handleBlur = () => {
  // 验证输入
  if (!code.value) {
    showError.value = true;
  }
};

// 获取验证码
const getCode = async (e) => {
  // 阻止事件冒泡和默认行为
  e.stopPropagation();
  e.preventDefault();
  
  if (codeNum.value > 0) return;
  
  codeNum.value = 60;

  timer.value = setInterval(() => {
    --codeNum.value;
    if (codeNum.value <= 0) {
      clearInterval(timer.value);
    }
  }, 1000);

  try {
    const res = await getVerifyCode({ username: store.userName });
    if (res.statusCode === 200) {
      showSuccessToast(res.message);
    }
  } catch (error) {
    //
  }
};

// 处理提交操作
const handleSubmit = (e) => {
  // 阻止事件冒泡和默认行为
  e.stopPropagation();
  e.preventDefault();
  
  // 验证输入
  if (!code.value) {
    showError.value = true;
    // 获取焦点
    nextTick(() => {
      forceFocus();
    });
    return;
  }
  
  // 执行提交
  onSubmit();
};

// 提交
const onSubmit = async () => {
  loading.value = true;

  try {
    store.captchaCode = code.value;
    await store.getReading(true, store.userName);

    if (!store.readShow) {
      router.push({ path: '/confirm-dialog', query: { type: '2' } });
    } else {
      const res = await store.getLoginverification({ username: store.userName, verify_code: code.value });

      if (res.statusCode === 200) {
        const redirect = route.query.redirect as string;
        router.push({
          path: redirect || '/menu/worksheets'
        });
        store.getPermission();
      }
    }
  } catch (error) {
    //
  } finally {
    loading.value = false;
  }
};

// 在组件卸载时移除监听器
onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value);
  }
  
  // 移除事件监听
  window.removeEventListener('resize', adjustViewForKeyboard);
  document.removeEventListener('click', handleDocumentClick);
  
  if (isIOS.value) {
    document.removeEventListener('touchend', handleIOSTouch);
    document.removeEventListener('touchmove', (e) => e.preventDefault(), { passive: false });
    
    if (isSafari.value) {
      document.removeEventListener('focusin', handleIOSFocusIn);
    }
  }
  
  // 恢复页面设置
  document.body.style.position = '';
  document.body.style.width = '';
  document.body.style.height = '';
  document.body.style.overflow = '';
});
</script>

<style lang="scss" scoped>
.login-container {
  width: 100%;
  height: 100%;
  background-image: url('@/assets/image/bg-lightgray.png');
  background-size: cover;
  display: flex;
  flex-direction: column;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  /* 防止iOS回弹效果 */
  -webkit-overflow-scrolling: none;
  overflow: hidden;

  .login-img {
    width: 100%;
    height: 50px;
    background: #fff;
    display: flex;
    justify-content: space-between;
    align-items: center;

    img {
      height: 32px;
      margin-left: 10px;
    }
  }

  .login-form {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    overflow-y: auto;
    padding: 10px 0;
    /* 禁用iOS橡皮筋效果 */
    overscroll-behavior: none;

    .card-content {
      width: 330px;
      padding: 5px 5px 0;
      background: #fff;
      box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.12);
      border-radius: 4px;
      margin: auto;
      
      /* 优化Safari渲染 */
      transform: translateZ(0);
      -webkit-transform: translateZ(0);

      .login-title {
        font-size: 18px;
        text-align: center;
        font-weight: 600;
      }

      .login-desc {
        font-size: 12px;
        color: #909399;
        padding: 0 20px 0 40px;
      }
      
      .form-container {
        padding: 0;
      }
      
      .input-group {
        margin-top: 10px;
        background-color: transparent;
        border: none;
        box-shadow: none;
        
        .custom-input-wrapper {
          display: flex;
          align-items: center;
          width: 100%;
          padding: 0 10px;
          box-sizing: border-box;
          height: 56px;
        }
        
        /* 自定义输入框容器 */
        .custom-input-container {
          position: relative;
          flex: 1;
          margin-right: 10px;
          height: 100%;
          display: flex;
          align-items: center;

          .name-top-icon {
            position: absolute;
            top: 50%;
            left: 16px;
            transform: translateY(-50%);
            z-index: 1;
          }
          
          .custom-input {
            width: 100%;
            height: 32px;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            padding-left: 35px;
            font-size: 12px;
            outline: none;
            box-sizing: border-box;
            /* Safari特有样式 */
            -webkit-appearance: none;
            appearance: none;
          }
          
          .error-message {
            position: absolute;
            bottom: -12px;
            left: 10px;
            color: #bf1920;
            font-size: 12px;
          }
        }
      }

      .captcha {
        font-size: 13px;
        width: 90px;
        height: 30px;
        flex-shrink: 0;
        // margin-top: 2px;
        box-sizing: border-box;
        padding: 0;
        border-radius: 2px;
      }
    }
  }
}

/* Safari特有样式 */
@supports (-webkit-touch-callout: none) {
  .login-container {
    height: -webkit-fill-available;
  }
}

:deep(.van-cell-group) {
  background-color: transparent !important;
  margin: 0 !important;
  padding: 0 !important;
  box-shadow: none !important;
}

:deep(.van-cell-group__inset) {
  margin: 0 !important;
  border-radius: 0 !important;
}

:deep(.van-cell) {
  padding: 0 !important;
  background-color: transparent !important;
}
</style>